package app.imttf.online.backing.buatttf;

import app.imttf.online.adfextensions.ADFUtils;
import app.imttf.online.adfextensions.JSFUtils;
import app.imttf.online.backing.admin.user.UserData;
import app.imttf.online.model.OnlineTtfAMImpl;

import app.imttf.online.model.view.admin.access.UserCabangViewImpl;
import app.imttf.online.model.view.admin.access.UserCabangViewRowImpl;
import app.imttf.online.model.view.buatttf.InfoSupplierAttrbViewImpl;
import app.imttf.online.model.view.buatttf.InfoSupplierAttrbViewRowImpl;
import app.imttf.online.model.view.buatttf.NpwpIndomarcoViewImpl;
import app.imttf.online.model.view.buatttf.NpwpIndomarcoViewRowImpl;
import app.imttf.online.model.view.buatttf.TtfHeaderGetKeyViewImpl;
import app.imttf.online.model.view.buatttf.TtfHeaderGetKeyViewRowImpl;
import app.imttf.online.model.view.buatttf.TtfHeaderUpdateStatusViewImpl;
import app.imttf.online.model.view.buatttf.TtfHeaderUpdateStatusViewRowImpl;
import app.imttf.online.model.view.info.FlagPkpViewImpl;
import app.imttf.online.model.view.info.FlagPkpViewRowImpl;
import app.imttf.online.model.view.buatttf.upload.TtfBpbViewImpl;
import app.imttf.online.model.view.buatttf.upload.TtfFpViewImpl;
import app.imttf.online.model.view.buatttf.upload.ValidateSupCodeBranchViewImpl;
import app.imttf.online.model.view.deletettf.DeleteTtfBpbWhenCancelViewImpl;
import app.imttf.online.model.view.deletettf.DeleteTtfFpWhenCancelViewImpl;
import app.imttf.online.model.view.deletettf.DeleteTtfHeaderWhenCancelViewImpl;
import app.imttf.online.model.view.param.ParamGlobalViewImpl;
import app.imttf.online.model.view.param.ParamGlobalViewRowImpl;
import app.imttf.online.model.view.ttf.TtfHeaderViewImpl;

import java.io.IOException;
import java.io.InputStream;

import javax.faces.event.ValueChangeEvent;

import oracle.adf.model.binding.DCIteratorBinding;

import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import java.util.Random;

import javax.faces.application.FacesMessage;

import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.input.RichSelectOneChoice;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import oracle.jbo.JboException;
import oracle.jbo.Row;

import org.apache.myfaces.trinidad.event.ReturnEvent;
import org.apache.myfaces.trinidad.model.UploadedFile;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class BuatTtfBackingBean {

    private RichInputText itSupCode;
    private String birtUrl;
    private String keyTtf;
    private String keyFpBpb;
    private String newKeyFpBpb;
    private StringBuilder dateNowStr;
    private SimpleDateFormat keyDateFormat = new SimpleDateFormat("ddMMyyyy");
    private UploadedFile _file;
    private RichSelectOneChoice cabangOption;
    private RichSelectOneChoice supplierOption;
    private RichTable tableTtfPkp;
    private final String MSG_NO_NWPW_IDM =
        "No. NPWP Indomarco sesuai cabang tidak ditemukan";
    private final String MSG_WRONG_XLS_FORMAT =
        "Terdeteksi ada pengisian yang tidak sesuai format pada file excel, mohon ikuti panduan untuk pengisian TTF secara online";
    private final String MSG_NO_SUP_CODE =
        "Terdeteksi ada lembar/sheet excel kosong atau kode supplier tidak terisi";
    private final String MSG_NO_SUP_CODE_CHOICE =
        "Pilihan Kode supplier tidak boleh dikosongkan";
    private final String MSG_NO_CAB_CODE_CHOICE =
        "Pilihan Cabang Indomarco tidak boleh dikosongkan";
    private final String MSG_USER_NO_CAB =
        "User yang memiliki hak untuk membuat TTF wajib memiliki opsi cabang minimal satu";
    private final String MSG_WRONG_SUP_CODE_1 = "Terdeteksi kode supplier ";
    private final String MSG_WRONG_SUP_CODE_2 =
        " tidak termasuk dalam cabang ";
    private final String MSG_WRONG_SUP_CODE_3 =
        " pada batas kewenangan anda menginput data";
    private final String MSG_OVER_SUP_CODE =
        "Terdeteksi ada kesalahan penulisan kode supplier atau kode supplier berada diluar batas kewenangan anda untuk menginput data";
    private final String BIRT_URL = "BIRT-URL";
    private final String BIRT_PORT = "BIRT-PORT";
    private final String MSG_URL_BIRT_PARAM_NOT_FOUND =
        "Parameter URL BIRT Report Server tidak ditemukan";
    private final String MSG_PORT_BIRT_PARAM_NOT_FOUND =
        "Parameter PORT BIRT Report Server tidak ditemukan";
    private OnlineTtfAMImpl onlineTtfAMImpl =
        (OnlineTtfAMImpl)ADFUtils.getApplicationModuleForDataControl("OnlineTtfAMDataControl");

    public UploadedFile getFile() {
        return _file;
    }

    public void setFile(UploadedFile file) {
        _file = file;
    }

    public void setCabangOption(RichSelectOneChoice cabangOption) {
        this.cabangOption = cabangOption;
    }

    public RichSelectOneChoice getCabangOption() {
        return cabangOption;
    }

    public BuatTtfBackingBean() {
    }

    private String getPkpFlagBySupCode(String supCode) {
        FlagPkpViewImpl flagPkpViewImpl = onlineTtfAMImpl.getFlagPkpView1();

        flagPkpViewImpl.setsupcode(supCode);
        flagPkpViewImpl.executeQuery();
        FlagPkpViewRowImpl flagPkpRow =
            (FlagPkpViewRowImpl)flagPkpViewImpl.first();

        String flag = flagPkpRow.getFlagPkp();
        return flag;
    }

    public String addOnlineTTF() {

        String randKeyTtf = String.valueOf(randNumKeyTtf());
        String randKeyFpBpb = String.valueOf(randNumKeyFpBpb());

        DCIteratorBinding cabangIter =
            ADFUtils.getDCBindingContainer().findIteratorBinding("UserCabangView1Iterator");
        int cabangIndex = (Integer)cabangOption.getValue();
        Row cabangRow = cabangIter.getRowAtRangeIndex(cabangIndex);
        String branchCode = (String)cabangRow.getAttribute("BranchCode");

        if (branchCode.isEmpty() || branchCode == null) {
            this.showWarning(MSG_NO_CAB_CODE_CHOICE);
        }

        DCIteratorBinding supplierIter =
            ADFUtils.getDCBindingContainer().findIteratorBinding("LovSupplier1Iterator");
        int supplierIndex = (Integer)supplierOption.getValue();
        Row supplierRow = supplierIter.getRowAtRangeIndex(supplierIndex);
        String supCode = (String)supplierRow.getAttribute("VendorSiteCode");

        if (supCode.isEmpty() || supCode == null) {
            this.showWarning(MSG_NO_SUP_CODE_CHOICE);
        }

        String pkpNonFlag;
        String npwpSup;

        OnlineTtfAMImpl onlineTtfAM =
            (OnlineTtfAMImpl)ADFUtils.getApplicationModuleForDataControl("OnlineTtfAMDataControl");

        Date dateNow = new Date();
        dateNowStr = new StringBuilder(keyDateFormat.format(dateNow));

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        pkpNonFlag = supplierType(onlineTtfAM, supCode).trim();
        npwpSup = supplierNpwp(onlineTtfAM, supCode).trim();

        // Generate key TTF
        keyTtf = generateKeyTtf(branchCode, supCode, dateNowStr, randKeyTtf);
        keyFpBpb =
                generateKeyFpBpb(keyTtf, dateNowStr, pkpNonFlag, randKeyFpBpb);

        // Create new TTF Header
        // PARAM: offlineTtfAM, SupSiteCode, Npwp, KeyTtf, BranchCode
        createNewHeader(onlineTtfAM, supCode, npwpSup, keyTtf, branchCode);

        // Put variable into pageflow
        pageFlowScope.put("supCode", supCode);
        pageFlowScope.put("keyTtf", keyTtf);
        pageFlowScope.put("keyFpBpb", keyFpBpb);
        pageFlowScope.put("tipeSup", pkpNonFlag);
        pageFlowScope.put("npwpSup", npwpSup);
        pageFlowScope.put("npwpIdm",
                          npwpPkpIndomarco(onlineTtfAM, branchCode));
        pageFlowScope.put("kodeDc", branchCode);

        onlineTtfAM.getDBTransaction().commit();

        return "newTtf";
    }

    public String buatTtfAction() throws IOException {

        String pkpNonFlag = "";
        String npwpSup = "";
        String previousNoFp = "";

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        // check user's supplier code
        UserData userData =
            (UserData)JSFUtils.resolveExpression("#{UserData}");
        String userSupCode = userData.getSupCodeLabel();

        String[] userSupCodeArray = userSupCode.split(", ");
        List<String> supCodeList = Arrays.asList(userSupCodeArray);

        String pkpFlag = this.getPkpFlagBySupCode(supCodeList.get(0));

        InputStream is = this.getFile().getInputStream();

        Date now = new Date();

        TtfHeaderViewImpl ttfHeaderView1 = onlineTtfAMImpl.getTtfHeaderView1();
        TtfFpViewImpl ttfFpViewImpl = onlineTtfAMImpl.getTtfFpView1();
        TtfBpbViewImpl ttfBpbViewImpl = onlineTtfAMImpl.getTtfBpbView1();

        HSSFWorkbook wb = new HSSFWorkbook(is);
        int sheetNum = wb.getNumberOfSheets();

        List xlsSupCodeList = new ArrayList();
        for (int h = 0; h < sheetNum; h++) {
            try {
                xlsSupCodeList.add(wb.getSheetAt(h).getRow(0).getCell(1).getStringCellValue());
            } catch (Exception e) {
                this.showWarning(MSG_NO_SUP_CODE);
            }
        }

        if (supCodeList.containsAll(xlsSupCodeList)) {
            DCIteratorBinding cabangIter =
                ADFUtils.getDCBindingContainer().findIteratorBinding("UserCabangView1Iterator");

            int cabangIndex = (Integer)cabangOption.getValue();
            Row cabangRow = cabangIter.getRowAtRangeIndex(cabangIndex);

            // Get branch code from input option
            String branchCode = (String)cabangRow.getAttribute("BranchCode");

            if (validateSupCodeBranch(branchCode, xlsSupCodeList)) {

                // read per sheet
                for (int h = 0; h < sheetNum; h++) {
                    HSSFSheet ws = wb.getSheetAt(h);

                    String randKeyTtf = String.valueOf(randNumKeyTtf());

                    String kodeSupplier =
                        ws.getRow(0).getCell(1).getStringCellValue();

                    pkpNonFlag =
                            supplierType(onlineTtfAMImpl, kodeSupplier).trim();
                    npwpSup =
                            supplierNpwp(onlineTtfAMImpl, kodeSupplier).trim();

                    Date dateNow = new Date();
                    dateNowStr =
                            new StringBuilder(keyDateFormat.format(dateNow));

                    // Generate key TTF
                    keyTtf =
                            generateKeyTtf(branchCode, kodeSupplier, dateNowStr,
                                           randKeyTtf);

                    int rowNum = ws.getLastRowNum() + 1;

                    Row ttfHeaderRow = ttfHeaderView1.createRow();
                    ttfHeaderRow.setAttribute("KeyTtf", keyTtf);
                    ttfHeaderRow.setAttribute("TtfDate", now);
                    ttfHeaderRow.setAttribute("SupSiteCode", kodeSupplier);
                    ttfHeaderRow.setAttribute("Npwp", npwpSup);
                    ttfHeaderRow.setAttribute("BranchCode", branchCode);

                    // read per row
                    for (int i = 2; i < rowNum; i++) {
                        HSSFRow row = ws.getRow(i);

                        // read per column
                        if ("Y".equals(pkpFlag)) {
                            if ((previousNoFp.equals("")) ||
                                !(row.getCell(2).getStringCellValue().equals(previousNoFp))) {

                                String randKeyFpBpb =
                                    String.valueOf(randNumKeyFpBpb());
                                keyFpBpb =
                                        generateKeyFpBpb(keyTtf, dateNowStr, pkpNonFlag,
                                                         randKeyFpBpb);
                                Row ttfFpRow = ttfFpViewImpl.createRow();
                                /*
                            System.out.println("---------------------------------");
                            System.out.println("JNS FP : |" + row.getCell(1).getStringCellValue().toString() + "|");
                            System.out.println("NO FP  : |" + row.getCell(2).getStringCellValue().toString() + "|");
                            System.out.println("AMT DPP: |" + row.getCell(4).getStringCellValue().toString() + "|");
                            System.out.println("AMT TAX: |" + row.getCell(5).getStringCellValue().toString() + "|");
                            System.out.println("TGL FP : |" + row.getCell(3).getStringCellValue().toString() + "|");
                            System.out.println("---------------------------------");
                            */
                                ttfFpRow.setAttribute("JenisFp",
                                                      row.getCell(1).getStringCellValue());
                                ttfFpRow.setAttribute("NoFp",
                                                      row.getCell(2).getStringCellValue());
                                ttfFpRow.setAttribute("TglFp",
                                                      row.getCell(3).getDateCellValue());
                                ttfFpRow.setAttribute("AmountDpp",
                                                      row.getCell(4).getNumericCellValue());
                                ttfFpRow.setAttribute("AmountTax",
                                                      row.getCell(5).getNumericCellValue());
                                ttfFpRow.setAttribute("KeyTtf", keyTtf);
                                ttfFpRow.setAttribute("KeyFpBpb", keyFpBpb);
                                ttfFpRow.setAttribute("NoPkpSup", npwpSup);
                                ttfFpRow.setAttribute("NoPkpIdm",
                                                      npwpPkpIndomarco(onlineTtfAMImpl,
                                                                       branchCode));
                                ttfFpViewImpl.insertRow(ttfFpRow);
                                previousNoFp =
                                        row.getCell(2).getStringCellValue();

                            }

                            Row ttfBpbRow = ttfBpbViewImpl.createRow();
                            ttfBpbRow.setAttribute("InvoiceNum",
                                                   row.getCell(0).getStringCellValue());
                            ttfBpbRow.setAttribute("KeyTtf", keyTtf);
                            ttfBpbRow.setAttribute("KeyFpBpb", keyFpBpb);
                            ttfBpbViewImpl.insertRow(ttfBpbRow);
                            pageFlowScope.put("tipeSup", pkpNonFlag);

                        } else {

                            String randKeyFpBpb =
                                String.valueOf(randNumKeyFpBpb());
                            keyFpBpb =
                                    generateKeyFpBpb(keyTtf, dateNowStr, pkpNonFlag,
                                                     randKeyFpBpb);

                            Row ttfBpbRow = ttfBpbViewImpl.createRow();
                            ttfBpbRow.setAttribute("InvoiceNum",
                                                   row.getCell(0).getStringCellValue());
                            ttfBpbRow.setAttribute("KeyTtf", keyTtf);
                            ttfBpbRow.setAttribute("KeyFpBpb", keyFpBpb);
                            ttfBpbViewImpl.insertRow(ttfBpbRow);
                            pageFlowScope.put("tipeSup", pkpNonFlag);

                        }
                    }
                }

                try {
                    onlineTtfAMImpl.getDBTransaction().commit();
                } catch (JboException ex) {
                    this.showWarning(MSG_WRONG_XLS_FORMAT);
                    onlineTtfAMImpl.getDBTransaction().rollback();
                }
            }
        } else {
            this.showError(MSG_OVER_SUP_CODE);
        }
        return "reviewTtf";
    }

    public void setItSupCode(RichInputText itSupCode) {
        this.itSupCode = itSupCode;
    }

    public RichInputText getItSupCode() {
        return itSupCode;
    }

    private String generateKeyTtf(String branchCode, String supCode,
                                  StringBuilder dateNowStr, String randKey) {
        String keyTtf;

        // Key TTF format: (BRANCH CODE)(SUP CODE)(DDMMYYYYHHMISS)
        keyTtf =
                branchCode.concat(supCode.concat(dateNowStr.toString().concat(randKey)));

        return keyTtf;

    }

    private String generateKeyFpBpb(String keyTtf, StringBuilder dateNowStr,
                                    String pkpNonFlag, String randKey) {
        String keyFbBpb;

        // Key FP - BPB format: (BRANCH CODE)(SUP CODE)(DDMMYYYYHHMISS)(FB)(DDMMYYYYHHMISS)
        if (pkpNonFlag.equalsIgnoreCase("Y")) {
            keyFbBpb =
                    keyTtf.concat("FB".concat(dateNowStr.toString().concat(randKey)));
        } else {
            keyFbBpb = keyTtf.concat("FB00000000000000");
        }

        return keyFbBpb;
    }

    private String supplierType(OnlineTtfAMImpl onlineTtfAM, String supCode) {
        String tipeSup = "";

        InfoSupplierAttrbViewImpl infoSupplierView =
            onlineTtfAM.getInfoSupplierAttrbView1();
        infoSupplierView.setsupCode(supCode);
        infoSupplierView.executeQuery();

        InfoSupplierAttrbViewRowImpl infoSuppRow =
            (InfoSupplierAttrbViewRowImpl)infoSupplierView.first();
        tipeSup = infoSuppRow.getFlagPkp();

        return tipeSup;
    }

    private String supplierNpwp(OnlineTtfAMImpl onlineTtfAM, String supCode) {
        String supNpwp = "";

        InfoSupplierAttrbViewImpl infoSupplierView =
            onlineTtfAM.getInfoSupplierAttrbView1();
        infoSupplierView.setsupCode(supCode);
        infoSupplierView.executeQuery();

        InfoSupplierAttrbViewRowImpl infoSuppRow =
            (InfoSupplierAttrbViewRowImpl)infoSupplierView.first();
        supNpwp = infoSuppRow.getNoPkp();

        return supNpwp;
    }

    private void createNewHeader(OnlineTtfAMImpl onlineTtfAM,
                                 String SupSiteCode, String Npwp,
                                 String KeyTtf, String BranchCode) {

        java.sql.Timestamp timeStamp =
            new java.sql.Timestamp(System.currentTimeMillis());
        oracle.jbo.domain.Date dateTime =
            new oracle.jbo.domain.Date(timeStamp);

        TtfHeaderViewImpl ttfHeaderView = onlineTtfAM.getTtfHeaderView1();
        Row ttfHeaderRow = ttfHeaderView.createRow();
        ttfHeaderRow.setAttribute("TtfDate", dateTime);
        ttfHeaderRow.setAttribute("SupSiteCode", SupSiteCode);
        ttfHeaderRow.setAttribute("Npwp", Npwp);
        ttfHeaderRow.setAttribute("Status", "DRAFT");
        ttfHeaderRow.setAttribute("KeyTtf", KeyTtf);
        ttfHeaderRow.setAttribute("BranchCode", BranchCode);
        ttfHeaderView.insertRow(ttfHeaderRow);

        onlineTtfAM.getDBTransaction().commit();
    }

    public void setSupplierOption(RichSelectOneChoice supplierOption) {
        this.supplierOption = supplierOption;
    }

    public RichSelectOneChoice getSupplierOption() {
        return supplierOption;
    }

    public void setNewKeyFpBpb(String newKeyFpBpb) {
        this.newKeyFpBpb = newKeyFpBpb;
    }

    public String getNewKeyFpBpb() {
        String pkpNonFlag;

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        String keyTtf = (String)pageFlowScope.get("keyTtf");
        String supCode = (String)pageFlowScope.get("supCode");

        Date dateNow = new Date();
        dateNowStr = new StringBuilder(keyDateFormat.format(dateNow));

        String fpBpbSuffix =
            (dateNowStr.toString()).concat(String.valueOf(randNumKeyFpBpb()));

        pkpNonFlag = supplierType(onlineTtfAMImpl, supCode).trim();

        // Key FP - BPB format: (BRANCH CODE)(SUP CODE)(DDMMYYYYHHMISS)(FB)(DDMMYYYYHHMISS)
        if (pkpNonFlag.equalsIgnoreCase("Y")) {
            newKeyFpBpb = keyTtf.concat("FB".concat(fpBpbSuffix));
        } else {
            newKeyFpBpb = keyTtf.concat("FB0000000000000000000");
        }

        return newKeyFpBpb;
    }

    private String npwpPkpIndomarco(OnlineTtfAMImpl onlineTtfAM,
                                    String branchCode) {

        String npwpIdm;

        NpwpIndomarcoViewImpl npwpIndomarcoView;
        npwpIndomarcoView = onlineTtfAM.getNpwpIndomarcoView1();
        npwpIndomarcoView.setbranchCode(branchCode);
        npwpIndomarcoView.executeQuery();

        long npwpIndomarcoNumRow = npwpIndomarcoView.getEstimatedRowCount();

        if (npwpIndomarcoNumRow == 0) {
            showError(MSG_NO_NWPW_IDM);
            npwpIdm = "000.000-00.00000000";
        } else {
            NpwpIndomarcoViewRowImpl npwpIndomarcoRow =
                (NpwpIndomarcoViewRowImpl)npwpIndomarcoView.first();
            npwpIdm = npwpIndomarcoRow.getNoPkp();
        }

        return npwpIdm;
    }

    public void noTtfToPageflow() {

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        String keyTtf = (String)pageFlowScope.get("keyTtf");

        TtfHeaderGetKeyViewImpl ttfHeaderGetKeyView =
            onlineTtfAMImpl.getTtfHeaderGetKeyView1();
        ttfHeaderGetKeyView.setkeyTtf(keyTtf);
        ttfHeaderGetKeyView.executeQuery();

        TtfHeaderGetKeyViewRowImpl ttfHeaderGetKeyRow =
            (TtfHeaderGetKeyViewRowImpl)ttfHeaderGetKeyView.first();
        String numTtf = ttfHeaderGetKeyRow.getTtfNum();

        pageFlowScope.put("numTtf", numTtf);

    }


    public void updateTtfStatusReview() {

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        String keyTtf = (String)pageFlowScope.get("keyTtf");

        TtfHeaderUpdateStatusViewImpl ttfHeaderUpdateStatusView =
            onlineTtfAMImpl.getTtfHeaderUpdateStatusView1();
        ttfHeaderUpdateStatusView.setkeyTtf(keyTtf);
        ttfHeaderUpdateStatusView.executeQuery();

        long ttfHeaderUpdateStatusNumRow =
            ttfHeaderUpdateStatusView.getEstimatedRowCount();

        if (ttfHeaderUpdateStatusNumRow > 0) {
            TtfHeaderUpdateStatusViewRowImpl ttfHeaderUpdateStatusRow =
                (TtfHeaderUpdateStatusViewRowImpl)ttfHeaderUpdateStatusView.first();
            ttfHeaderUpdateStatusRow.setStatus("REVIEW");
            onlineTtfAMImpl.getDBTransaction().commit();
        }
    }

    public void updateTtfStatusCancel() {

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        String keyTtf = (String)pageFlowScope.get("keyTtf");

        OnlineTtfAMImpl onlineTtfAM =
            (OnlineTtfAMImpl)ADFUtils.getApplicationModuleForDataControl("OnlineTtfAMDataControl");

        DeleteTtfHeaderWhenCancelViewImpl deleteTtfHeaderWhenCancelView =
            onlineTtfAM.getDeleteTtfHeaderWhenCancelView1();
        deleteTtfHeaderWhenCancelView.setkeyTtf(keyTtf);
        deleteTtfHeaderWhenCancelView.executeQuery();

        long deleteTtfHeaderWhenCancelNumRow =
            deleteTtfHeaderWhenCancelView.getEstimatedRowCount();

        if (deleteTtfHeaderWhenCancelNumRow > 0) {
            deleteTtfBpb(onlineTtfAM, keyTtf);
            deleteTtfFp(onlineTtfAM, keyTtf);
            
            Row row;
            while ((row = deleteTtfHeaderWhenCancelView.next()) != null) {
                row.remove();
            }
            onlineTtfAM.getDBTransaction().commit();
        } else {
            TtfHeaderUpdateStatusViewImpl ttfHeaderUpdateStatusView =
                onlineTtfAM.getTtfHeaderUpdateStatusView1();
            ttfHeaderUpdateStatusView.setkeyTtf(keyTtf);
            ttfHeaderUpdateStatusView.executeQuery();

            long ttfHeaderUpdateStatusNumRow =
                ttfHeaderUpdateStatusView.getEstimatedRowCount();

            if (ttfHeaderUpdateStatusNumRow > 0) {
                TtfHeaderUpdateStatusViewRowImpl ttfHeaderUpdateStatusRow =
                    (TtfHeaderUpdateStatusViewRowImpl)ttfHeaderUpdateStatusView.first();
                ttfHeaderUpdateStatusRow.setStatus("CANCEL");
                onlineTtfAM.getDBTransaction().commit();
            }
        }
    }

    public void updateTtfStatusDraft() {

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        String keyTtf = (String)pageFlowScope.get("keyTtf");

        TtfHeaderUpdateStatusViewImpl ttfHeaderUpdateStatusView =
            onlineTtfAMImpl.getTtfHeaderUpdateStatusView1();
        ttfHeaderUpdateStatusView.setkeyTtf(keyTtf);
        ttfHeaderUpdateStatusView.executeQuery();

        long ttfHeaderUpdateStatusNumRow =
            ttfHeaderUpdateStatusView.getEstimatedRowCount();

        if (ttfHeaderUpdateStatusNumRow > 0) {
            TtfHeaderUpdateStatusViewRowImpl ttfHeaderUpdateStatusRow =
                (TtfHeaderUpdateStatusViewRowImpl)ttfHeaderUpdateStatusView.first();
            ttfHeaderUpdateStatusRow.setStatus("DRAFT");
            onlineTtfAMImpl.getDBTransaction().commit();
        }
    }

    public void onDialogReturn(ReturnEvent returnEvent) {
        BindingContext bctx = BindingContext.getCurrent();
        DCBindingContainer binding =
            (DCBindingContainer)bctx.getCurrentBindingsEntry();
        DCIteratorBinding iter =
            (DCIteratorBinding)binding.get("VerifikasiNewTtfPkpView1Iterator");
        iter.executeQuery();

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        adfFacesContext.addPartialTarget(tableTtfPkp);
    }

    public void setTableTtfPkp(RichTable tableTtfPkp) {
        this.tableTtfPkp = tableTtfPkp;
    }

    public RichTable getTableTtfPkp() {
        return tableTtfPkp;
    }

    public static int randNumKeyFpBpb() {
        Random rand = new Random();
        int randomNum = rand.nextInt((999999 - 100000) + 1) + 100000;
        return randomNum;
    }

    public static int randNumKeyTtf() {
        Random rand = new Random();
        int randomNum = rand.nextInt((999999 - 100000) + 1) + 100000;
        return randomNum;
    }

    public String showError(String msg) {
        FacesMessage fm = new FacesMessage(msg);
        /**
                 * set the type of the message.
                 * Valid types: error, fatal,info,warning
                 */
        fm.setSeverity(FacesMessage.SEVERITY_ERROR);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
        return null;
    }

    public String showMessage(String msg) {
        FacesMessage fm = new FacesMessage(msg);
        /**
             * set the type of the message.
             * Valid types: error, fatal,info,warning
             */
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
        return null;
    }

    public String showWarning(String msg) {
        FacesMessage fm = new FacesMessage(msg);
        /**
             * set the type of the message.
             * Valid types: error, fatal,info,warning
             */
        fm.setSeverity(FacesMessage.SEVERITY_WARN);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, fm);
        return null;
    }

    public void firstCabang() {

        //Get branch code from user data
        UserData userData =
            (UserData)JSFUtils.resolveExpression("#{UserData}");
        String userNameLogin = userData.getUserNameLogin();

        UserCabangViewImpl userCabang =
            (UserCabangViewImpl)onlineTtfAMImpl.getUserCabangView1();
        userCabang.setuserName(userNameLogin);
        userCabang.executeQuery();

        UserCabangViewRowImpl userCabangRow =
            (UserCabangViewRowImpl)userCabang.first();

        String firstBranchCode = "000";
        try {
            firstBranchCode = userCabangRow.getBranchCode();
        } catch (Exception e) {
            this.showError(MSG_USER_NO_CAB);
        }

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();
        pageFlowScope.put("userBranch", firstBranchCode);

    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public void branchChange(ValueChangeEvent valueChangeEvent) {

        DCIteratorBinding cabangIter =
            ADFUtils.getDCBindingContainer().findIteratorBinding("UserCabangView1Iterator");
        int cabangIndex = (Integer)valueChangeEvent.getNewValue();
        Row cabangRow = cabangIter.getRowAtRangeIndex(cabangIndex);
        String branchCode = (String)cabangRow.getAttribute("BranchCode");

        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();
        pageFlowScope.put("userBranch", branchCode);

        BindingContainer bindings = getBindings();
        OperationBinding operationBinding =
            bindings.getOperationBinding("ExecuteWithParams");
        operationBinding.execute();

        adfFacesContext.addPartialTarget(supplierOption);

    }

    private boolean validateSupCodeBranch(String branchCd,
                                          List xlsSupCodeList) {
        boolean allValid = false;
        for (int i = 0; i < xlsSupCodeList.size(); i++) {
            ValidateSupCodeBranchViewImpl validateSupCodeBranchView =
                onlineTtfAMImpl.getValidateSupCodeBranchView1();
            validateSupCodeBranchView.setbranchCode(branchCd);
            validateSupCodeBranchView.setsupCode((String)xlsSupCodeList.get(i));
            validateSupCodeBranchView.executeQuery();

            if (validateSupCodeBranchView.getEstimatedRowCount() == 0) {
                this.showError(MSG_WRONG_SUP_CODE_1 + xlsSupCodeList.get(i) +
                               MSG_WRONG_SUP_CODE_2 + branchCd +
                               MSG_WRONG_SUP_CODE_3);
                allValid = false;
                break;
            } else {
                allValid = true;
            }
        }

        return allValid;
    }

    public void valInputType(String inputType) {
        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        pageFlowScope.put("inputType", inputType);
    }
    
    private String getBirtHost() {
        String hostStr = "";

        ParamGlobalViewImpl birtHost =
            (ParamGlobalViewImpl)onlineTtfAMImpl.getParamGlobalView1();
        birtHost.setparamType(BIRT_URL);
        birtHost.executeQuery();

        long birtHostRowNum = birtHost.getEstimatedRowCount();

        if (birtHostRowNum > 0) {
            ParamGlobalViewRowImpl birtHostRow =
                (ParamGlobalViewRowImpl)birtHost.first();
            hostStr = birtHostRow.getParamValue().trim();
        } else {
            this.showError(MSG_URL_BIRT_PARAM_NOT_FOUND);
        }

        return hostStr;
    }

    private String getBirtPort() {
        String portStr = "";

        ParamGlobalViewImpl birtPort =
            (ParamGlobalViewImpl)onlineTtfAMImpl.getParamGlobalView1();
        birtPort.setparamType(BIRT_PORT);
        birtPort.executeQuery();

        long birtPortRowNum = birtPort.getEstimatedRowCount();

        if (birtPortRowNum > 0) {
            ParamGlobalViewRowImpl birtPortRow =
                (ParamGlobalViewRowImpl)birtPort.first();
            portStr = birtPortRow.getParamValue().trim();
        } else {
            this.showError(MSG_PORT_BIRT_PARAM_NOT_FOUND);
        }

        return portStr;
    }

    public void setBirtUrl(String birtUrl) {
        this.birtUrl = birtUrl;
    }

    public String getBirtUrl() {
        String birtUrl = getBirtHost().trim().concat((":").concat(getBirtPort().trim()));
        return birtUrl;
    }

    private void deleteTtfBpb(OnlineTtfAMImpl onlineTtfAM, String keyTtf) {
        DeleteTtfBpbWhenCancelViewImpl deleteTtfBpbWhenCancelView =
            onlineTtfAM.getDeleteTtfBpbWhenCancelView1();
        deleteTtfBpbWhenCancelView.setkeyTtf(keyTtf);
        deleteTtfBpbWhenCancelView.executeQuery();

        long deleteTtfBpbWhenCancelNumRow =
            deleteTtfBpbWhenCancelView.getEstimatedRowCount();

        if (deleteTtfBpbWhenCancelNumRow > 0) {
            Row row;
            while ((row = deleteTtfBpbWhenCancelView.next()) != null) {
                row.remove();
            }
            onlineTtfAM.getDBTransaction().commit();
        }

    }

    private void deleteTtfFp(OnlineTtfAMImpl onlineTtfAM, String keyTtf) {
        DeleteTtfFpWhenCancelViewImpl deleteTtfFpWhenCancelView =
            onlineTtfAM.getDeleteTtfFpWhenCancelView1();
        deleteTtfFpWhenCancelView.setkeyTtf(keyTtf);
        deleteTtfFpWhenCancelView.executeQuery();

        long deleteTtfFpWhenCancelNumRow =
            deleteTtfFpWhenCancelView.getEstimatedRowCount();

        if (deleteTtfFpWhenCancelNumRow > 0) {
            Row row;
            while ((row = deleteTtfFpWhenCancelView.next()) != null) {
                row.remove();
            }
            onlineTtfAM.getDBTransaction().commit();
        }
    }
}
